import request from '../../../utils/request'

Page({
  data: {
    tab: 0, // 0=全部，1=待上门
    list: [],
    loading: false,
    wxUserId: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取全局用户ID
    const app = getApp();
    const wxUserId = app.globalData.userId || wx.getStorageSync('userId');
    
    if (!wxUserId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ wxUserId: wxUserId });
    // 加载预约列表
    this.loadAppointments();
  },

  /**
   * 页面显示时刷新数据
   */
  onShow() {
    if (this.data.wxUserId) {
      this.loadAppointments();
    }
  },

  /**
   * 加载预约列表
   */
  loadAppointments() {
    const that = this;
    const { wxUserId, tab } = this.data;
    
    // 调试日志：打印当前用户ID
    console.log('当前用户ID:', wxUserId);
    
    // 根据tab获取状态筛选
    let status = '';
    if (tab === 1) {
      status = '1'; // 只查询待上门（待确认）的预约
    }
    
    this.setData({ loading: true });
    wx.showLoading({ title: '加载中...' });
    
    // 构建请求URL
    let url = `/le/registration/myAppointments?wxUserId=${wxUserId}`;
    if (status) {
      url += `&status=${status}`;
    }
    
    // 调试日志：打印请求URL
    console.log('请求URL:', url);
    
    request({
      url: url,
      method: 'GET',
      success: (res) => {
        console.log('预约列表返回：', res);
        wx.hideLoading();
        
        if (res.statusCode === 200 && res.data.code === 200) {
          // 格式化数据
          const list = that.formatAppointments(res.data.data || []);
          
          that.setData({
            list: list,
            loading: false
          });
        } else {
          that.setData({ loading: false });
          wx.showToast({
            title: res.data.msg || '加载失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('加载预约失败：', err);
        wx.hideLoading();
        that.setData({ loading: false });
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 格式化预约数据
   */
  formatAppointments(appointments) {
    return appointments.map(item => {
      // 格式化日期时间
      const appointmentTime = new Date(item.appointmentTime);
      const date = this.formatDate(appointmentTime);
      const time = this.formatTime(appointmentTime);
      
      return {
        id: item.id,
        date: date,
        type: this.convertType(item.appointmentType),
        time: time,
        status: this.convertStatus(item.status),
        statusCode: item.status, // 保存原始状态码
        name: item.applicantName || '',
        family: '', // 如果需要显示家人信息，需要从接口获取
        phone: item.phone || ''
      };
    });
  },

  /**
   * 格式化日期
   */
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}.${month}.${day}`;
  },

  /**
   * 格式化时间
   */
  formatTime(date) {
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    return `${hour}:${minute}`;
  },

  /**
   * 转换预约类型
   */
  convertType(type) {
    const typeMap = {
      '0': '参观预约',
      '1': '探访预约'
    };
    return typeMap[type] || '未知';
  },

  /**
   * 转换预约状态
   */
  convertStatus(status) {
    const statusMap = {
      '1': '待上门',
      '2': '已过期',
      '3': '已完成',
      '4': '已取消'
    };
    return statusMap[status] || '未知';
  },

  /**
   * 切换Tab
   */
  changeTab(e) {
    const tab = parseInt(e.currentTarget.dataset.tab);
    this.setData({ tab: tab }, () => {
      this.loadAppointments();
    });
  },

  /**
   * 取消预约
   */
  cancel(e) {
    const that = this;
    const id = e.currentTarget.dataset.id;
    const wxUserId = this.data.wxUserId;
    
    wx.showModal({
      title: "提示",
      content: "确定要取消该预约吗？",
      confirmText: "确定取消",
      cancelText: "我再想想",
      success: (res) => {
        if (res.confirm) {
          that.processCancelAppointment(id, wxUserId);
        }
      }
    });
  },

  /**
   * 处理取消预约
   */
  processCancelAppointment(appointmentId, wxUserId) {
    const that = this;
    
    wx.showLoading({ title: '取消中...' });
    
    request({
      url: `/le/registration/cancelAppointment?appointmentId=${appointmentId}&wxUserId=${wxUserId}`,
      method: 'POST',
      success: (res) => {
        console.log('取消预约返回：', res);
        wx.hideLoading();
        
        if (res.statusCode === 200 && res.data.code === 200) {
          wx.showToast({
            title: '预约已取消',
            icon: 'success',
            duration: 2000
          });
          
          // 延迟刷新列表
          setTimeout(() => {
            that.loadAppointments();
          }, 2000);
        } else {
          wx.showToast({
            title: res.data.msg || '取消失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('取消预约失败：', err);
        wx.hideLoading();
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadAppointments();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});